import store from '../store';
import { Message } from 'element-ui'
let WEBSOCKET = {
  lockReconnect: false,//避免重复连接
  wsUrl:"ws://127.0.0.1:8086",
  // wsUrl:"wss://tsocket.sysush.com",
  tt: null,
  eventHub:null,
  init(eventHub) {
    this.eventHub = eventHub;
    this.createWebSocket();
  },
  createWebSocket() {
    let _this = this;
    try {
      store.commit("SET_WEBSOCKET",new WebSocket(_this.wsUrl))
      _this.sockectEvent();
    } catch (e) {
      console.log(e);
      _this.reconnect();
    }
  },
  sockectEvent() {
    let _this = this;
    store.state.WEBSOCKET.onclose = function() {
      console.log('刷卡websocket-链接关闭');
      _this.reconnect();
    };
    store.state.WEBSOCKET.onerror = function() {
      console.log('刷卡websocket-发生异常了');
      _this.reconnect();
    };
    store.state.WEBSOCKET.onopen = function() {
      console.log("刷卡websocket-链接成功")
    };

    store.state.WEBSOCKET.addEventListener("message",(event)=>{
      let data = JSON.parse(event.data);
      console.log(data)
      if(data.plcc.cmdType=="ReadCardBasYB"){ //刷医保卡事件
        let info = data.data ||"";
        if(info.indexOf("|")>-1){ //成功
        
          // "440300|340827199310154981|B91452116|440300D1560000052009C690A28E3E20|张林玉|0081544C97868444032009C690|3.00|20210922|20310922|000000000000|59059B3500E826E8|"
          _this.eventHub.$emit("ReadCard_Back",{
            code: 0,
            WYBS:  info.split("|")[1], //医保卡
            BSLX: 4 
          });

        }else{ //失败
          _this.eventHub.$emit("ReadCard_Back",{
            code: -1,
            msg: info,//错误信息
            WYBS:  "", 
            BSLX: 4 
          });

        }
      }else if (data.plcc.cmdType=='ReadSFZYB') {
        let info = data.data ||"";
        if(info.indexOf("^")>-1){//成功
          _this.eventHub.$emit("ReadCard_Back",{
            code: 0,
            WYBS:  info.split("^")[0], //身份证号
            BSLX: 3
          });
        }else{//失败
          _this.eventHub.$emit("ReadCard_Back",{
            code: -1,
            msg: info,//错误信息
            WYBS:  "", 
            BSLX: 3
          });

        }
      }

      //广播事件
      _this.eventHub.$emit(data.plcc.cmdType,data)

      // if(data.type == 'SOCKET_HEART_BEAT') {
      //   if(data.code == 0) {
      //     console.log(data.list);
      //     store.commit("SET_ONLINE_NUM",data.totalNum);
      //     store.commit("SET_ONLINE_USERLIST",data.list);
      //   }else{
      //     console.log("心跳包：")
      //     console.log(data);
      //     if(data.code == -1) {
      //       Message({
      //         showClose: true,
      //         message:'您还未登录账号，或在其他窗口已经退出登录',
      //         type: 'error',
      //         duration: 4 * 1000
      //       });
      //     }else if(data.code==-2) {
      //       Message({
      //         showClose: true,
      //         message:'您的帐号在另一地点登录，您已被迫下线',
      //         type: 'error',
      //         duration: 4 * 1000
      //       });
      //     }else if(data.code==-3) {
      //       Message({
      //         showClose: true,
      //         message:'登录过期，请重新登录',
      //         type: 'error',
      //         duration: 4 * 1000
      //       });
      //     }
      //     setTimeout(()=>{

      //       store.commit('SET_ISLOGIN', false)
      //       store.commit('SET_TOKEN', '')
      //       window.localStorage.clear()
      //       store.dispatch('delAllViews')
      //       location.reload()// In order to re-instantiate the vue-router object to avoid bugs
      //       // store.dispatch('LogOut').then(() => {
      //       //   store.dispatch('delAllViews')
      //       //   location.reload()// In order to re-instantiate the vue-router object to avoid bugs
      //       // });
      //     },4000)
      //     return false;
      //   }
      // }else{
      //   console.log("发送成功: "+data.type);
      //   console.log(data)
      // }
    
      
    });
  },
  reconnect() {
    //处理调试阶段的特殊情况 没有退出就进入登录页面导致socket没有关闭问题
    if(window.location.hash.indexOf("#/login")>-1){
      store.commit("SET_WEBSOCKET",null)
      return false; 
    }
    let _this = this;
    if (_this.lockReconnect) {
      return;
    };
    _this.lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    _this.tt && clearTimeout(_this.tt);
    _this.tt = setTimeout(function() {
      _this.createWebSocket();
      _this.lockReconnect = false;
    }, 40000);
  },
  // //医保卡
  // SEND_ReadCardBasYB(){
  //   store.state.WEBSOCKET.send('{"plcc":{"cmdType":"ReadCardBasYB","plccType":"SSCARD-MHAH-31"},"param":{}}');
  // },
  // //身份证
  // ReadSFZYB(){
  //   store.state.WEBSOCKET.send('{"plcc":{"cmdType":"ReadSFZYB","plccType":"SSCARD-MHAH-31"},"param":{}}');
  // },
  // //医保读扫码信息
  // GetQRBaseYB(){
  //   store.state.WEBSOCKET.send('{"plcc":{"cmdType":"ReadSFZYB","plccType":"SSCARD-MHAH-31"},"param":{}}');
  // },
  // // //发送消息封装
  // // send(obj) {
  // //   store.state.WEBSOCKET.send(JSON.stringify({
  // //     ...obj,
  // //     token: store.state.token,
  // //     loginID: store.state.userId
  // //   }))
  // // }
}

export default WEBSOCKET;
